import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import { createForm } from 'rc-form'
import {
    List,
    ListView,
    NavBar,
    Icon,
    Flex,
    SearchBar,
    Button,
    WhiteSpace,
} from 'antd-mobile';
import { R, ORDER_STATUSES, subjects } from "@/assets/js/dict"
import { GetPublishedOrders } from "@/api/tutor/orderList.js";
import './orderList.scss';
import _ from "lodash";
const Item = List.Item;
const Brief = Item.Brief;

let params = { pageSize: 7, pageNum: 1 };

/**
 * 可供报名的订单列表
 * @param props
 * @returns {*}
 * @constructor
 */
function OrderMarket (props) {

    const { getFieldProps } = props.form;
    const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    params.tutor_id = userInfo.id;


    /*
    * 订单数据
    * */
    let [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }));
    let [orders, setOrders] = useState([]);

    //后台返回的分页数据
    let [records, setRecords] = useState({});


    let [word, setWord] = useState("加载中...");
    let [isLoading, setisLoading] = useState(true);

    //科目
    let [subs, setSubs] = useState(() => {
        return _.cloneDeep(subjects)
    });


    //课时费
    const fee_selects = [{ name: '不限', fee_mix: null, fee_max: null, checked: true },
    { name: '100以下', fee_mix: null, fee_max: 10000, checked: false },
    { name: '100-300', fee_mix: 10000, fee_max: 30000, checked: false },
    { name: '300以上', fee_mix: 30000, fee_max: null, checked: false }
    ];

    let [fee, setFee] = useState(() => {
        return _.cloneDeep(fee_selects)
    });

    //课时费选择，单选效果
    function feeClick (index) {
        let item;
        for (let i = 0; i < fee.length; i++) {
            item = fee[i];
            item.checked = i === index;
            if (i === index) {
                params.fee_max = item.fee_max;
                params.fee_mix = item.fee_mix;
            }
        }
        setFee([...fee]);
    }

    //搜索栏是否占据100%宽度
    let [full, setFull] = useState(false);

    //高级搜索的显隐
    let [showAdvanced, updateShowAdvanced] = useState(false);

    function trans () {
        updateShowAdvanced(!showAdvanced);
    }


    function getOrders (_params) {
        console.log("getOrders--> ", _params);
        let params = _.cloneDeep(_params);
        let subjectDicts = params.subjects, subjects = null;
        if (subjectDicts) {
            for (let i in subjectDicts) {
                if (subjectDicts[i]) {
                    if (subjects === null) {
                        subjects = subjectDicts[i];
                    } else {
                        subjects = subjects + "," + subjectDicts[i];
                    }
                }
            }
            params.subjects = subjects;
        }
        GetPublishedOrders(params).then(re => {
            if (R.isSuccess(re)) {
                let data = R.getData(re);

                if (!!data.dataList) {
                    let currentPageNum = data.pageIndex;
                    if (currentPageNum === 1) {
                        setRecords(data);
                        orders = [...data.dataList];
                    } else {
                        if (data.dataList.length > 0) {
                            setRecords(data);
                            orders.push(...data.dataList);
                        }
                    }
                    setOrders(orders);
                    let d = dataSource.cloneWithRows(orders);
                    setDataSource(d);
                    setisLoading(false);
                    if (data.pageIndex === data.totalPage || data.dataList.length === 0) {
                        setWord("亲，没有更多了");
                    } else {
                        setWord("已加载");
                    }
                } else {
                    setWord("亲，没有更多了");
                }
            }
        }).catch(err => {
            console.error(err);
        });
    }


    useEffect(() => {
        getOrders(params);
    }, []);

    //加载数据
    let onEndReached = (event) => {
        if (isLoading || records.pageIndex === records.totalPage) {
            setWord("亲，没有更多了");
            return;
        } else {
            setisLoading(true);
            setWord("加载中...");
            params.pageNum = records.pageIndex + 1;
            getOrders(params);
        }
    };

    const separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );

    const row = (rowData, sectionID, rowID) => {

        /*
        * 正在教学的订单
        * */
        return (
            <div key={rowID + rowData.id} style={{ padding: '0 15px' }}>
                <Item key={rowData.id}
                    arrow="horizontal"
                    multipleLine
                    onClick={() => {
                        sessionStorage.setItem("order_id", rowData.id);
                        props.history.push({
                            pathname: '/orderDetails',
                            data: rowData
                        })
                    }}
                    platform="cross"
                >
                    {rowData.subjects}
                    <strong style={{
                        color: 'orange',
                        float: 'right'
                    }}
                    >课时费：{rowData.class_fee ? rowData.class_fee / 100 + "￥" : ''}</strong>
                    <Brief> 家长姓名：{rowData.parent_name}</Brief>
                    <Brief> 地址：{rowData.learn_address}</Brief> 
                    <Brief> 辅导科目：{rowData.subjects}</Brief>
                </ Item>
            </div>
        )
    };

    //科目选择
    function subsClick (index) {
        let source = subs[index];
        source.checked = !source.checked;
        if (source.checked) {
            (params['subjects'] || (params['subjects'] = {}))[source.name] = source.name;
        } else {
            (params['subjects'] || (params['subjects'] = {}))[source.name] = null;
        }
        setSubs([...subs]);
    }

    let handle = {};

    function search (val) {
        params.val = val;
        params.pageNum = 1;
        getOrders(params);
    }

    //搜索栏获取焦点事件处理
    function searchFocus () {
        setFull(true);
    }

    //搜索栏失去焦点事件处理
    function searchBlur () {
        setFull(false);
    }

    //清空搜索栏中的值
    function clearSearchBar () {
        params["val"] = null;
    }


    //返回按键
    function goBack () {
        props.history.goBack()
    }

    /**
     * 保存搜索栏的实例
     * @param ref
     */
    function storeSearchRef (ref) {
        handle["searcher"] = ref
    }

    //关闭或者取消高级搜索
    function closeAdvancedSearch () {

        //清理选择的查询条件
        setSubs(_.cloneDeep(subjects));
        setFee(_.cloneDeep(fee_selects));
        params.pageNum = 1;

        params.fee_max = 10000000;
        params.fee_mix = -1;
        params.subjects = "";
        getOrders(params);

        //关闭筛选界面
        updateShowAdvanced(false);
    }

    //高级搜索
    function advancedSearch () {
        console.log("advancedSearch---->");

        //隐藏搜索页，展示结果页
        updateShowAdvanced(false);
        params.pageNum = 1;
        console.log("advancedSearch---> ", params);
        getOrders(params);
    }

    /**
     * 渲染页脚
     * @param word
     * @returns {*}
     */
    function renderFooter () {
        return (<div style={{ padding: 30, textAlign: 'center' }}>{word}</div>)
    }

    return (
        <div>
            <div className="order-details orderMarket" style={{ display: showAdvanced ? 'block' : 'none' }}>
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="cross" />}
                        onLeftClick={closeAdvancedSearch}
                    >
                        筛选
                    </NavBar>
                </div>

                <div className="page-content  home-content">
                    <div className="publish-content-piece">
                        <div className="form-box">
                            <div>
                                <strong>
                                    科目：
                                </strong>
                            </div>
                            <WhiteSpace size="lg" />
                            <div className="form-con">
                                {subs.map((item, index) => {
                                    return (
                                        <Button inline style={{ marginLeft: '0.5em' }} key={index}
                                            onClick={() => subsClick(index)} size="small"
                                            type={item.checked ? 'primary' : 'ghost'}
                                        >{item.name}</Button>
                                    );
                                })}
                            </div>
                            <WhiteSpace size="lg" />
                            <div>
                                <strong>
                                    课时费（元/时）：
                                </strong>
                            </div>
                            <WhiteSpace size="lg" />
                            <div className="form-con">
                                {fee.map((item, index) => {
                                    return (
                                        <Button inline style={{ marginLeft: '0.5em' }} key={index}
                                            onClick={() => feeClick(index)} size="small"
                                            type={item.checked ? 'primary' : 'ghost'}
                                        >{item.name}</Button>
                                    );
                                })}
                            </div>
                            <WhiteSpace size="xl" />
                            <WhiteSpace size="xl" />
                            <div className="form-con">
                                <Flex justify={"center"}>
                                    <Flex.Item style={{ flexGrow: 1 }}><Button size="small"
                                        onClick={closeAdvancedSearch}
                                    >取消</Button></Flex.Item>
                                    <Flex.Item style={{ flexGrow: 2 }}><Button size="small" type="primary"
                                        onClick={advancedSearch}
                                    >确定</Button></Flex.Item>
                                </Flex>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="order-details orderMarket" style={{ display: !showAdvanced ? 'block' : 'none' }}>
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                    // icon={<Icon type="left" />}
                    // onLeftClick={goBack}
                    >
                        发布的订单
                    </NavBar>
                </div>


                <div className="page-content  home-content">

                    <div className="publish-content-piece">

                        <div style={{ marginLeft: '1%', marginRight: '1%' }}>
                            <Flex justify={"center"}>
                                <Flex.Item style={{ flexGrow: 3 }}>
                                    <SearchBar showCancelButton cancelText="查询"
                                        maxLength={20}
                                        onFocus={searchFocus}
                                        onBlur={searchBlur}
                                        onClear={clearSearchBar}
                                        onSubmit={search}
                                        onCancel={search}
                                        placeholder="请输入"
                                        ref={storeSearchRef}
                                    />
                                </Flex.Item>
                                {full ? '' : <Flex.Item style={{ flexGrow: 1 }}>
                                    <Button type="primary" size="small" onClick={trans}>条件筛选</Button>
                                </Flex.Item>}
                            </Flex>

                        </div>

                        <ListView
                            dataSource={dataSource}
                            renderFooter={renderFooter}
                            renderRow={row}
                            renderSeparator={separator}
                            className="am-list"
                            pageSize={4}
                            useBodyScroll
                            onScroll={(e) => {
                                console.log('scroll', e);
                            }}
                            scrollRenderAheadDistance={500}
                            onEndReached={onEndReached}
                            onEndReachedThreshold={10}
                        />
                    </div>

                </div>
            </div>
        </div>

    );

}

OrderMarket = createForm()(OrderMarket);
export default withRouter(OrderMarket);